package com.ruoyi.mobile.project.sms.service;

import com.ruoyi.db.sms.domain.SmsCoupon;
import com.ruoyi.db.sms.domain.SmsCouponUser;
import com.ruoyi.mobile.project.utils.CouponConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class WxCouponVerifyService
{

    @Autowired
    private WxSmsCouponUserService couponUserService;

    @Autowired
    private WxSmsCouponService couponService;

    /**
     * 检测优惠券是否适合
     *
     * @param userId
     * @param couponId
     * @param checkedGoodsPrice
     * @return
     */
    public SmsCoupon checkCoupon(Long userId, Long couponId, Long userCouponId, BigDecimal checkedGoodsPrice)
    {
        SmsCoupon coupon = couponService.findById(couponId);
        if (coupon == null)
        {
            return null;
        }

        SmsCouponUser couponUser = couponUserService.findById(userCouponId);
        if (couponUser == null)
        {
            couponUser = couponUserService.queryOne(userId, couponId);
        }
        else if (!couponId.equals(couponUser.getCouponId()))
        {
            return null;
        }

        if (couponUser == null)
        {
            return null;
        }

        // 检查是否超期
        Integer timeType = coupon.getTimeType();
        Integer days = coupon.getDays();
        LocalDateTime now = LocalDateTime.now();
        if (timeType.equals(CouponConstant.TIME_TYPE_TIME))
        {
            if (now.isBefore(coupon.getStartTime()) || now.isAfter(coupon.getEndTime()))
            {
                return null;
            }
        }
        else if (timeType.equals(CouponConstant.TIME_TYPE_DAYS))
        {
            LocalDateTime expired = couponUser.getAddTime().plusDays(days);
            if (now.isAfter(expired))
            {
                return null;
            }
        }
        else
        {
            return null;
        }

        // 检测商品是否符合
        // TODO 目前仅支持全平台商品，所以不需要检测
        Integer goodType = coupon.getGoodsType();
        if (!goodType.equals(CouponConstant.GOODS_TYPE_ALL))
        {
            return null;
        }

        // 检测订单状态
        Integer status = coupon.getStatus();
        if (!status.equals(CouponConstant.STATUS_NORMAL))
        {
            return null;
        }

        // 检测是否满足最低消费
        if (checkedGoodsPrice.compareTo(coupon.getMinimum()) == -1)
        {
            return null;
        }

        return coupon;
    }

}
